package org.darkforest.admin.controller;

import org.darkforest.common.services.OrderBillService;
import org.darkforest.common.services.OrderService;
import org.darkforest.common.services.OrderStatisService;
import org.darkforest.common.services.PdLogService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 销量统计分析
 * Created by Administrator on 2016/1/27.
 */
@RequestMapping(value = "statistics")
@Controller
public class SalesVolumeStatController {

    final static String[] days = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
    final static String[] hours = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
//    final static String[] weeds = {"1", "2", "3", "4", "5", "6", "7"};
//    final static String[] top50 = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
//            "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
//            "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
//            "31", "32", "33", "34", "35", "36", "37", "38", "39", "40",
//            "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"};


    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private OrderStatisService orderStatisService;

    @Autowired
    private PdLogService pdLogService;


    @Autowired
    private OrderBillService orderBillService;

    @Autowired
    private OrderService orderService;


    /**
     * 销售收入统计列表
     *
     * @param start
     * @param year
     * @param month
     * @return
     */
    @RequestMapping(value = "salesAnalysis")
    public ModelAndView saleIncome(@RequestParam(required = false, defaultValue = "1") int start,
                                   String year, String month) {
        ModelAndView res = new ModelAndView("statistics/sale/salesAnalysis");
        OrderStatis orderStatis = new OrderStatis();
        orderStatis.setStart(start);
        if ((!"".equals(year)) && year != null) {
            orderStatis.setOsYear(new Short(year));
            if ((!"".equals(month)) && month != null) {
                orderStatis.setOsMonth(Integer.parseInt(year + month));
            }
        } else {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.MONTH, -1);
            year = c.get(Calendar.YEAR) + "";
            month = c.get(Calendar.MONTH) + 1 + "";
            if (c.get(Calendar.MONTH) < 10) {
                month = "0" + month;
            }
            orderStatis.setOsYear(new Short(year));
            orderStatis.setOsMonth(Integer.parseInt(year + month));
        }
        OrderBill orderBill = new OrderBill();
        orderBill.setOsMonth(orderStatis.getOsMonth());
        orderBill.setStart(start);
        orderBill.setResultList(orderBillService.selectByCondition(orderBill));
        orderStatis = orderStatisService.selectByPrimaryKey(orderStatis.getOsMonth());
        res.addObject("orderStatis", orderStatis);
        res.addObject("page", orderBill);
        res.addObject("month", month);
        res.addObject("year", year);
        return res;
    }


    /**
     * 预存款统计
     *
     * @param pdType      预存款类型
     * @param startTime   统计开始时间 --3自定义时间统计
     * @param endTime     统计结束时间 --3自定义时间统计
     * @param searchType  统计类型 1按某个日期统计 2按月统计
     * @param searchDay   1按某个日期统计
     * @param searchYear  2按月统计
     * @param searchMonth 2按月统计
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "salesAnalysis/predeposit")
    public ModelAndView predeposit(@RequestParam(required = false, defaultValue = "deposit") String pdType,
                                   @RequestParam(required = false, defaultValue = "") String startTime,
                                   @RequestParam(required = false, defaultValue = "") String endTime,
                                   @RequestParam(required = false, defaultValue = "1") String searchType,
                                   @RequestParam(required = false, defaultValue = "") String searchDay,
                                   @RequestParam(required = false, defaultValue = "") String searchYear,
                                   @RequestParam(required = false, defaultValue = "") String searchMonth) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        ModelAndView res = new ModelAndView("statistics/sale/pre_deposit_analysis");
        res.addObject("searchType", searchType);
        res.addObject("pdType", pdType);


        //初始化查询条件
        PdLogSearchBean searchBean = new PdLogSearchBean();

        Map<String, Object> staticsMap = new HashMap<String, Object>();
        List<PdLogVo> pdLogList = new ArrayList<PdLogVo>();
        if ("1".equals(searchType)) { //按天查询
            searchDay = "".equals(searchDay) ? sdf.format(new Date()) : searchDay;
            calendar.setTime(DateUtil.strToDate(searchDay, "yyyy-MM-dd"));
            searchBean.setAddTime(sdf.format(calendar.getTime()));
            searchBean.setLgType(pdType);
            searchBean.setSearchType(searchType);
            //折线图数据
            Map<String, Object> pdLog_first = pdLogService.statisticsPdLogByDay(searchBean); //选择统计的日期
            //列表数据
            pdLogList = pdLogService.selectListByDay(searchBean);
            //统计数据
            staticsMap = pdLogService.statisticsByDay(searchBean);

            res.addObject("firstDay", searchDay);
            res.addObject("first", pdLog_first);
            calendar.add(calendar.DATE, -1);
            searchBean.setAddTime(sdf.format(calendar.getTime()));
            Map<String, Object> pdLog_secend = pdLogService.statisticsPdLogByDay(searchBean);//选择统计的日期的前一天
            res.addObject("second", pdLog_secend);
            res.addObject("lastDay", sdf.format(calendar.getTime()));
            res.addObject("searchDay", searchDay);
            res.addObject("hours", hours);


        } else if ("2".equals(searchType)) { //按月查询
            searchYear = "".equals(searchYear) ? calendar.get(Calendar.YEAR) + "" : searchYear;
            searchMonth = "".equals(searchMonth) ? calendar.get(Calendar.MONTH) + 1 + "" : searchMonth;

            res.addObject("searchYear", searchYear);
            res.addObject("searchMonth", searchMonth);

            //将传入的条件计算传入的某年的某个月有多少天
            int firstDays = getMonthDays(Integer.parseInt(searchYear), Integer.parseInt(searchMonth));
            //将查询条件返回到页面作为折线图一条线的下标
            res.addObject("firstMonth", searchYear + "-" + searchMonth);

            searchBean.setAddTime(searchYear + "-" + searchMonth);
            searchBean.setSearchType(searchType);
            searchBean.setLgType(pdType);
            Map<String, Object> pdLog_first = pdLogService.statisticsPdLogByMonth(searchBean); //选择统计的月份

            staticsMap = pdLogService.statisticsByMonth(searchBean);
            pdLogList = pdLogService.selectListByMonth(searchBean);


            calendar.setTime(DateUtil.strToDate(searchYear + "-" + searchMonth + "-01", "yyyy-MM-dd"));
            calendar.add(Calendar.MONTH, -1);
            if (calendar.get(Calendar.MONTH) + 1 < 10) {
                searchMonth = "0" + (calendar.get(Calendar.MONTH) + 1);
            } else {
                searchMonth = calendar.get(Calendar.MONTH) + 1 + "";
            }
            searchBean.setAddTime(calendar.get(Calendar.YEAR) + "-" + searchMonth);
            Map<String, Object> pdLog_second = pdLogService.statisticsPdLogByMonth(searchBean); //选择统计的月份
            int secondDays = getMonthDays(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
            if (firstDays > secondDays) {
                res.addObject("days", firstDays);
            } else {
                res.addObject("days", secondDays);
            }
            res.addObject("secondMonth", searchBean.getAddTime());
            res.addObject("first", pdLog_first);
            res.addObject("second", pdLog_second);

        } else {  //自定义日期查询

            startTime = "".equals(startTime) ? sdf.format(calendar.getTime()) : startTime;
            calendar.add(Calendar.DATE, -7);
            endTime = "".equals(endTime) ? sdf.format(calendar.getTime()) : endTime;
            res.addObject("startTime", startTime);
            res.addObject("endTime", endTime);
            int days = daysBetween(startTime, endTime);
            List<String> daysList = new ArrayList<String>();
            for (int i = 0; i <= days; i++) {
                calendar.setTime(DateUtil.strToDate(startTime, "yyyy-MM-dd"));
                calendar.add(Calendar.DATE, i);
                daysList.add(sdf.format(calendar.getTime()));
            }
            searchBean.setStime(DateUtil.toUnixTimeStampByDate(startTime) + "");
            searchBean.setEtime(DateUtil.toUnixTimeStampByDate(endTime) + "");
            searchBean.setLgType(pdType);
            Map<String, Object> spdlog = pdLogService.statisticsPdLogByCustom(searchBean);
            staticsMap = pdLogService.statisticsByCustom(searchBean);

            pdLogList = pdLogService.selectListByCustom(searchBean);

            res.addObject("title", startTime + "-" + endTime);
            res.addObject("daysList", daysList);
            res.addObject("pddata", spdlog);


        }
        res.addObject("statistics", staticsMap);
        res.addObject("pdlog", pdLogList);
        return res;
    }




//    /**
//     * 订单统计 首页默认
//     * @return
//     */
//    @RequestMapping(value = "salesAnalysis/order")
//    public ModelAndView order(){
//        ModelAndView res = new ModelAndView("statistics/sale/order_statics");
//        OrderSearchBean order = new OrderSearchBean();
//        order.setSearchDay(sdf.format(new Date()));
//        List<Order> orders =orderService.selectOrderListByDateCondition(order);
//
//        Map<String, Object> orderCountAndAmount =  orderService.staticsOrderCountAndAmountByDateCondition(order);
//
//
//
//        res.addObject("ordersList",orders);
//        res.addObject("orderCountAndAmount",orderCountAndAmount);
//        res.addObject("searchType","1");
//        res.addObject("searchDay",sdf.format(new Date()));
//
//        return res;
//    }







    /**
     * 销量分析---订单销售额分析
     *
     * @param orderState  订单状态统计
     * @param startTime   统计开始时间 按照时间段统计
     * @param endTime     统计结束时间 按照时间段统计
     * @param searchType  统计类型 1 按天统计  2按月统计 3 自定义时间统计
     * @param searchDay   按天统计
     * @param searchYear  按月统计
     * @param searchMonth 按月统计
     * @param storeName   店铺名称
     * @return
     */
    @RequestMapping(value = "salesAnalysis/order")
    public ModelAndView order(@RequestParam(required = false, defaultValue = "") String orderState,
                              @RequestParam(required = false, defaultValue = "") String startTime,
                              @RequestParam(required = false, defaultValue = "") String endTime,
                              @RequestParam(required = false, defaultValue = "1") String searchType,
                              @RequestParam(required = false, defaultValue = "") String searchDay,
                              @RequestParam(required = false, defaultValue = "") String searchYear,
                              @RequestParam(required = false, defaultValue = "") String searchMonth,
                              @RequestParam(required = false, defaultValue = "") String storeName) throws ParseException {
        ModelAndView res = new ModelAndView("statistics/sale/order_statics");
        OrderSearchBean order = new OrderSearchBean();
        order.setPageSwitch(false);
        order.setStoreName("".equals(storeName) ? null : storeName);
        order.setOrderState("".equals(orderState) ? null : orderState);
        res.addObject("storeName", storeName);
        res.addObject("orderState",orderState);
        res.addObject("searchType",searchType);
        Calendar calendar = Calendar.getInstance();


        List<Order> orders = new ArrayList<Order>();
        Map<String, Object> orderCountAndAmount = new HashMap<String, Object>();


        if ("1".equals(searchType)) { //按天统计

            searchDay = "".equals(searchDay)?sdf.format(new Date()):searchDay;
            res.addObject("searchDay",searchDay);

            order.setSearchDay(searchDay);
            calendar.setTime(DateUtil.strToDate(searchDay, "yyyy-MM-dd"));
            calendar.add(Calendar.DATE, -1);
            String yestoday = sdf.format(calendar.getTime());
            //订单列表
            orders =orderService.selectOrderListByDateCondition(order);
            //销量数据
            orderCountAndAmount =  orderService.staticsOrderCountAndAmountByDateCondition(order);


            Map<String, Object> first_amount = orderService.staticsOrderAmountByDateCondition(order);
            Map<String, Object> first_count = orderService.staticsOrderCountByDateCondition(order);
            order.setSearchDay(yestoday);
            Map<String, Object> last_amount = orderService.staticsOrderAmountByDateCondition(order);
            Map<String, Object> last_count = orderService.staticsOrderCountByDateCondition(order);


            res.addObject("dates",hours);
            res.addObject("firstAmount",first_amount);
            res.addObject("firstCount",first_count);
            res.addObject("lastCount",last_count);
            res.addObject("lastAmount",last_amount);
            res.addObject("firstTitle",searchDay);
            res.addObject("lastTitle",yestoday);

        } else if ("2".equals(searchType)) { //按月统计
            searchYear = "".equals(searchYear)?calendar.get(Calendar.YEAR)+"":searchYear;
            searchMonth = "".equals(searchMonth)?calendar.get(Calendar.MONTH)+1+"":searchMonth;
            res.addObject("searchYear", searchYear);
            res.addObject("searchMonth", searchMonth);
            order.setSearchMonth(searchYear + "-" + searchMonth);
            calendar.setTime(DateUtil.strToDate(order.getSearchMonth() + "-01", "yyyy-MM-dd"));
            calendar.add(Calendar.MONTH,-1);
            String lastMonth =  sdf.format(calendar.getTime());
            //订单列表
            orders =orderService.selectOrderListByDateCondition(order);
            //销量数据
            orderCountAndAmount =  orderService.staticsOrderCountAndAmountByDateCondition(order);

            Map<String, Object> first_amount = orderService.staticsOrderAmountByDateCondition(order);
            Map<String, Object> first_count = orderService.staticsOrderCountByDateCondition(order);
            order.setSearchMonth(lastMonth);
            Map<String, Object> last_amount = orderService.staticsOrderAmountByDateCondition(order);
            Map<String, Object> last_count = orderService.staticsOrderCountByDateCondition(order);

            res.addObject("dates",days);
            res.addObject("firstAmount",first_amount);
            res.addObject("firstCount",first_count);
            res.addObject("lastCount",last_count);
            res.addObject("lastAmount",last_amount);
            res.addObject("firstTitle",searchDay);
            res.addObject("lastTitle",lastMonth);

        } else { //按自定义时间统计

            endTime = "".equals(endTime)?sdf.format(new Date()):endTime;
            if("".equals(startTime)){
                calendar.add(Calendar.DATE,-7);
                startTime =sdf.format(calendar.getTime()) ;
            }

            order.setStartTime(startTime);
            order.setEndTime(endTime);
            int days = daysBetween(startTime, endTime);
            List<String> dateList = new ArrayList<String>();
            for(int i = 0 ;i<=days;i++){
                calendar.setTime(DateUtil.strToDate(startTime, "yyyy-MM-dd"));
                calendar.add(Calendar.DATE,i);
                dateList.add(sdf.format(calendar.getTime()) );
            }

            res.addObject("startTime",startTime);
            res.addObject("endTime",endTime);
            order.setSearchTimeQuantum(startTime+"--"+endTime);
            //订单列表
            orders =orderService.selectOrderListByDateCondition(order);
            //销量数据
            orderCountAndAmount =  orderService.staticsOrderCountAndAmountByDateCondition(order);

            Map<String, Object> first_amount = orderService.staticsOrderAmountByDateCondition(order);
            Map<String, Object> first_count = orderService.staticsOrderCountByDateCondition(order);

            res.addObject("dates",dateList);
            res.addObject("firstAmount",first_amount);
            res.addObject("firstCount",first_count);
            res.addObject("firstTitle",startTime+"--"+endTime);

        }



        res.addObject("orderList",orders);
        res.addObject("orderCountAndAmount",orderCountAndAmount);
        return res;
    }





    /**
     * 字符串的日期格式的计算
     */
    public static int daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }


    /*
     * 获取任意一年二月份的天数
	 */
    public static int getMonthDays(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 1);
        c.add(Calendar.DAY_OF_MONTH, -1);
        return c.getActualMaximum(Calendar.DAY_OF_MONTH);


    }

}
